<template>
  <div class="explore-container">
    <!-- 顶部导航 -->
    <div class="explore-header">
      <h1>🔍 探索发现</h1>
      <div class="header-actions">
        <el-button :icon="'RefreshRight'" @click="refreshContent">刷新</el-button>
        <el-button :icon="'User'" @click="goToProfile">个人中心</el-button>
      </div>
    </div>

    <!-- 主内容区 -->
    <div class="explore-content">
      <!-- 左侧：专家领域 + 热门话题 -->
      <div class="left-panel">
        <!-- 专家领域浏览 -->
        <el-card class="category-section" shadow="hover">
          <template #header>
            <div class="section-header">
              <span class="section-title">👨‍⚕️ 按专家领域浏览</span>
            </div>
          </template>
          <div class="category-list" v-loading="categoriesLoading">
            <div
              v-for="category in categories"
              :key="category.id"
              class="category-card"
              :class="{ active: selectedCategory === category.id }"
              @click="selectCategory(category.id)"
            >
              <div class="category-icon" :style="{ backgroundColor: category.color }">
                {{ category.icon }}
              </div>
              <div class="category-info">
                <h3>{{ category.name }}</h3>
                <p>{{ category.description }}</p>
                <span class="article-count">{{ category.articleCount }} 篇文章</span>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 热门话题 -->
        <el-card class="trending-section" shadow="hover">
          <template #header>
            <div class="section-header">
              <span class="section-title">🔥 热门话题</span>
            </div>
          </template>
          <div class="trending-list" v-loading="topicsLoading">
            <div
              v-for="topic in trendingTopics"
              :key="topic.id"
              class="trending-item"
              @click="viewTopic(topic)"
            >
              <div class="trending-icon">{{ topic.icon }}</div>
              <div class="trending-info">
                <h4>{{ topic.title }}</h4>
                <p>{{ topic.description }}</p>
                <div class="trending-meta">
                  <span>{{ topic.discussionCount }} 次讨论</span>
                  <el-tag
                    :type="topic.trend === 'up' ? 'danger' : topic.trend === 'down' ? 'info' : 'warning'"
                    size="small"
                  >
                    <el-icon v-if="topic.trend === 'up'"><CaretTop /></el-icon>
                    <el-icon v-else-if="topic.trend === 'down'"><CaretBottom /></el-icon>
                    <el-icon v-else><Minus /></el-icon>
                  </el-tag>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 右侧：为你推荐 -->
      <div class="right-panel">
        <el-card class="feed-section" shadow="hover">
          <template #header>
            <div class="section-header">
              <span class="section-title">✨ 为你推荐</span>
              <el-select v-model="feedFilter" size="small" style="width: 120px">
                <el-option label="全部" value="all" />
                <el-option label="文章" value="article" />
                <el-option label="话题" value="topic" />
              </el-select>
            </div>
          </template>

          <div class="feed-list" v-loading="feedLoading">
            <div
              v-for="item in filteredFeed"
              :key="item.id"
              class="feed-item"
            >
              <div v-if="item.type === 'article'" class="article-feed">
                <div class="article-cover" v-if="item.data.coverImage">
                  <img :src="item.data.coverImage" :alt="item.data.title" />
                </div>
                <div class="article-content">
                  <div class="article-header">
                    <h3 @click="viewArticle(item.data)">{{ item.data.title }}</h3>
                    <el-tag size="small" type="info">{{ getCategoryName(item.data.category) }}</el-tag>
                  </div>
                  <p class="article-summary">{{ item.data.summary }}</p>
                  <div class="article-meta">
                    <div class="author-info">
                      <el-avatar size="small" :icon="'UserFilled'" />
                      <span>{{ item.data.author }} · {{ item.data.authorTitle }}</span>
                    </div>
                    <div class="article-stats">
                      <span><el-icon><View /></el-icon> {{ formatNumber(item.data.readCount) }}</span>
                      <span><el-icon><Star /></el-icon> {{ formatNumber(item.data.likeCount) }}</span>
                    </div>
                  </div>
                  <div class="article-tags">
                    <el-tag
                      v-for="tag in item.data.tags"
                      :key="tag"
                      size="small"
                      type="info"
                      effect="plain"
                    >
                      {{ tag }}
                    </el-tag>
                  </div>
                  <div v-if="item.reason" class="recommend-reason">
                    <el-icon><Notification /></el-icon>
                    <span>{{ item.reason }}</span>
                  </div>
                </div>
              </div>
            </div>

            <el-empty
              v-if="filteredFeed.length === 0"
              description="暂无推荐内容"
              :image-size="120"
            />
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import {
  getExpertCategories,
  getCategoryArticles,
  getRecommendedFeed,
  getTrendingTopics
} from '@/api/explore';
import type { ExpertCategory, HealthArticle, TrendingTopic, FeedItem } from '@/types/explore';

const router = useRouter();

const categoriesLoading = ref(false);
const topicsLoading = ref(false);
const feedLoading = ref(false);

const categories = ref<ExpertCategory[]>([]);
const trendingTopics = ref<TrendingTopic[]>([]);
const feedItems = ref<FeedItem[]>([]);

const selectedCategory = ref<string>('');
const feedFilter = ref<string>('all');

// 过滤后的推荐内容
const filteredFeed = computed(() => {
  if (feedFilter.value === 'all') {
    return feedItems.value;
  }
  return feedItems.value.filter(item => item.type === feedFilter.value);
});

// 获取分类名称
const getCategoryName = (categoryId: string) => {
  const category = categories.value.find(c => c.id === categoryId);
  return category ? category.name : categoryId;
};

// 格式化数字
const formatNumber = (num: number) => {
  if (num >= 10000) {
    return (num / 10000).toFixed(1) + 'w';
  }
  return num.toString();
};

// 加载专家领域分类
const loadCategories = async () => {
  categoriesLoading.value = true;
  try {
    const response = await getExpertCategories();
    if (response.code === 200) {
      categories.value = response.data.categories;
    }
  } catch (error) {
    ElMessage.error('加载分类失败');
  } finally {
    categoriesLoading.value = false;
  }
};

// 加载热门话题
const loadTrendingTopics = async () => {
  topicsLoading.value = true;
  try {
    const response = await getTrendingTopics();
    if (response.code === 200) {
      trendingTopics.value = response.data.topics;
    }
  } catch (error) {
    ElMessage.error('加载热门话题失败');
  } finally {
    topicsLoading.value = false;
  }
};

// 加载推荐内容
const loadRecommendedFeed = async () => {
  feedLoading.value = true;
  try {
    const response = await getRecommendedFeed();
    if (response.code === 200) {
      feedItems.value = response.data.feed;
    }
  } catch (error) {
    ElMessage.error('加载推荐内容失败');
  } finally {
    feedLoading.value = false;
  }
};

// 选择分类
const selectCategory = async (categoryId: string) => {
  if (selectedCategory.value === categoryId) {
    selectedCategory.value = '';
    loadRecommendedFeed();
    return;
  }
  
  selectedCategory.value = categoryId;
  feedLoading.value = true;
  
  try {
    const response = await getCategoryArticles(categoryId);
    if (response.code === 200) {
      feedItems.value = response.data.articles.map(article => ({
        id: `feed_${article.id}`,
        type: 'article' as const,
        data: article
      }));
    }
  } catch (error) {
    ElMessage.error('加载文章失败');
  } finally {
    feedLoading.value = false;
  }
};

// 查看话题
const viewTopic = (topic: TrendingTopic) => {
  ElMessage.info(`查看话题: ${topic.title}`);
  // TODO: 跳转到话题详情页
};

// 查看文章
const viewArticle = (article: HealthArticle) => {
  ElMessage.info(`查看文章: ${article.title}`);
  // TODO: 跳转到文章详情页或在对话中询问
};

// 刷新内容
const refreshContent = () => {
  loadCategories();
  loadTrendingTopics();
  loadRecommendedFeed();
  ElMessage.success('刷新成功');
};

// 跳转到个人中心
const goToProfile = () => {
  router.push('/profile');
};

// 初始化
onMounted(() => {
  loadCategories();
  loadTrendingTopics();
  loadRecommendedFeed();
});
</script>

<style scoped lang="scss">
.explore-container {
  min-height: 100vh;
  background: #f5f7fa;
  padding: 20px;
}

.explore-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 12px;

  h1 {
    margin: 0;
    font-size: 24px;
    font-weight: 600;
  }

  .header-actions {
    display: flex;
    gap: 12px;
  }
}

.explore-content {
  display: grid;
  grid-template-columns: 400px 1fr;
  gap: 20px;
}

.left-panel {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .section-title {
    font-size: 16px;
    font-weight: 600;
  }
}

// 专家领域样式
.category-section {
  .category-list {
    display: flex;
    flex-direction: column;
    gap: 12px;

    .category-card {
      display: flex;
      gap: 12px;
      padding: 16px;
      border-radius: 8px;
      border: 2px solid transparent;
      cursor: pointer;
      transition: all 0.3s;

      &:hover {
        background: #f5f7fa;
      }

      &.active {
        border-color: #409eff;
        background: #ecf5ff;
      }

      .category-icon {
        width: 60px;
        height: 60px;
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 28px;
        flex-shrink: 0;
      }

      .category-info {
        flex: 1;

        h3 {
          margin: 0 0 4px 0;
          font-size: 16px;
          font-weight: 600;
        }

        p {
          margin: 0 0 8px 0;
          font-size: 13px;
          color: #909399;
        }

        .article-count {
          font-size: 12px;
          color: #409eff;
        }
      }
    }
  }
}

// 热门话题样式
.trending-section {
  .trending-list {
    display: flex;
    flex-direction: column;
    gap: 12px;

    .trending-item {
      display: flex;
      gap: 12px;
      padding: 12px;
      border-radius: 8px;
      cursor: pointer;
      transition: all 0.2s;

      &:hover {
        background: #f5f7fa;
      }

      .trending-icon {
        font-size: 24px;
        flex-shrink: 0;
      }

      .trending-info {
        flex: 1;

        h4 {
          margin: 0 0 4px 0;
          font-size: 14px;
          font-weight: 600;
        }

        p {
          margin: 0 0 8px 0;
          font-size: 12px;
          color: #909399;
        }

        .trending-meta {
          display: flex;
          justify-content: space-between;
          align-items: center;
          font-size: 12px;
          color: #909399;
        }
      }
    }
  }
}

// 推荐内容样式
.feed-section {
  .feed-list {
    display: flex;
    flex-direction: column;
    gap: 20px;

    .feed-item {
      .article-feed {
        display: flex;
        gap: 16px;
        padding: 16px;
        background: white;
        border-radius: 8px;
        border: 1px solid #e4e7ed;
        transition: all 0.3s;

        &:hover {
          box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
        }

        .article-cover {
          width: 200px;
          height: 120px;
          flex-shrink: 0;
          overflow: hidden;
          border-radius: 8px;

          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
        }

        .article-content {
          flex: 1;
          display: flex;
          flex-direction: column;

          .article-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 8px;

            h3 {
              margin: 0;
              font-size: 18px;
              font-weight: 600;
              cursor: pointer;
              flex: 1;

              &:hover {
                color: #409eff;
              }
            }
          }

          .article-summary {
            color: #606266;
            font-size: 14px;
            line-height: 1.6;
            margin-bottom: 12px;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
          }

          .article-meta {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 12px;

            .author-info {
              display: flex;
              align-items: center;
              gap: 8px;
              font-size: 13px;
              color: #606266;
            }

            .article-stats {
              display: flex;
              gap: 16px;
              font-size: 13px;
              color: #909399;

              span {
                display: flex;
                align-items: center;
                gap: 4px;
              }
            }
          }

          .article-tags {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
            margin-bottom: 8px;
          }

          .recommend-reason {
            display: flex;
            align-items: center;
            gap: 6px;
            font-size: 12px;
            color: #409eff;
            margin-top: auto;
          }
        }
      }
    }
  }
}

@media (max-width: 1200px) {
  .explore-content {
    grid-template-columns: 1fr;
  }

  .left-panel {
    order: 2;
  }

  .right-panel {
    order: 1;
  }
}

@media (max-width: 768px) {
  .explore-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;

    .header-actions {
      width: 100%;
      justify-content: flex-end;
    }
  }

  .article-feed {
    flex-direction: column !important;

    .article-cover {
      width: 100% !important;
      height: 180px !important;
    }
  }
}
</style>